import axios from 'axios'
import api from '../../api'
import { sessionStore } from '@/common/utils/storage'

const storeConfig = {
  state: {
    user: sessionStore.get('user'),
    token: sessionStore.get('token')
  },
  mutations: {
    Login (state, token) {
      state.token = token
    },
    LogOut (state) {
      state.token = ''
      state.user = ''
    },
    Set_User (state, user) {
      state.user = user
    }
  },
  actions: {
    login ({ commit }, userFormData) {
      return new Promise((resolve, reject) => {
        // 验证用户
        axios.request({
          url: 'api/user/login.action',
          method: 'POST',
          headers: { 'Content-Type': 'multipart/form-data' },
          withCredentials: true,
          data: userFormData
        })
          .then(resp => {
            const { token } = resp.data
            if (token) {
              // 持续存储token到本地
              sessionStore.set('token', token)
              commit('Login', token)
              resolve(resp)
            } else {
              reject(resp.data.msg)
            }
          })
          .catch(err => {
            commit('LogOut')
            sessionStore.remove('token')
            sessionStore.remove('user')
            reject(err.msg)
          })
      })
    },
    logout ({ commit }) {
      return new Promise((resolve, reject) => {
        api.post('api/user/logout.action')
          .then(response => {
            commit('LogOut')
            sessionStore.remove('token')
            sessionStore.remove('user')
            resolve(response)
          })
          .catch(error => {
            reject(error)
          })
      })
    },
    fetchUser ({ commit }) {
      return api({
        url: '/user/userInfo.action',
        method: 'GET'
      }).then((result) => {
        commit('Set_User', result)
        sessionStore.set('user', result)
      })
    }
  },
  getters: {
    userLogged: state => !!state.token
  }
}

export default storeConfig
